package api.action;

import api.model.ApiCollect;
import api.model.ApiConvertData;
import api.model.ApiConvertDataColumn;
import api.model.ApiTable;
import api.service.ApiConvertDataService;
import com.alibaba.fastjson.JSONObject;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.element.other.DisplayItem;
import m.html.form.*;
import m.html.list.ListButton;
import m.html.list.SuccessMethod;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;
import manage.action.StatusAction;
import manage.model.StatusModel;
import manage.util.DictionaryUtil;

import java.util.ArrayList;
import java.util.List;

@ActionMeta(name="api/apiConvertData")
public class ApiConvertDataAction extends StatusAction {
    private ApiConvertData model;
    private List<JSONObject> columnList;

    @Override
    public void doRecoveryCallback() throws Exception {
        getService(ApiConvertDataService.class).verifyEnable(this.model.getOid());
        getService(ApiConvertDataService.class).clearCache();
    }

    @Override
    public void doDisableCallback() throws Exception {
        getService(ApiConvertDataService.class).clearCache();
    }

    public JSONMessage doSave() throws Exception {
        systemLog("数据","保存数据转存");
        verifyAdminOperPower(getStatusPower());
        String msg=getService(ApiConvertDataService.class).save(model,columnList);
        return new JSONMessage(0,msg);
    }
    @RequestMeta(params = {"type"})
    public JSONMessage getTableOptions(String type) throws Exception {
        List<DisplayItem> tList= new ArrayList<>();
        if("source".equals(type)){
            List<ApiTable> ls= CacheUtil.getList(ApiTable.class,"");
            ls.forEach(item->{tList.add(DisplayItem.value(item.getOid(),item.getOid()+" - "+item.getDescription()));});
            List<ApiCollect> ls2=ModelQueryList.getModelList(ApiCollect.class,"*");
            ls2.forEach(item->{tList.add(DisplayItem.value(item.getOid(),item.getOid()+" - "+item.getDescription()));});
        }else if("save".equals(type)){
            List<ApiTable> ls= CacheUtil.getList(ApiTable.class,"Y,N,B");
            ls.forEach(item->{tList.add(DisplayItem.value(item.getOid(),item.getOid()+" - "+item.getDescription()));});
        }
        return DictionaryUtil.toDictData(tList);
    }
    @RequestMeta(params = {"oid"})
    public JSONMessage getSourceColumnOptions(String oid) throws MException {
        return DictionaryUtil.toDictData(getService(ApiConvertDataService.class).getSourceColumn(oid));
    }
    @RequestMeta(params = {"oid"})
    public JSONMessage getSaveColumnOptions(String oid) throws MException {
        return DictionaryUtil.toDictData(getService(ApiConvertDataService.class).getSaveColumn(oid));
    }
    /*
     * 编辑数据转存
     */
    public VueResult toEdit() throws Exception {
        verifyAdminOperPower(getStatusPower());//权限判断
        List<ApiConvertDataColumn> columnList;
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*");
            columnList=ModelQueryList.getModelList(ApiConvertDataColumn.class,new String[]{"*"},null, QueryCondition.eq("apiConvertData.oid",model.getOid()));
        }else{
            model=new ApiConvertData();
            model.setTriggerCondition("A");
            model.setTimerCondition("A");
            model.setTimerLong("1");
            model.setStatus(StatusModel.Status_Disabled);
            columnList=new ArrayList<>();
        }
        boolean edit=model.getStatus().equals("9");
        ModelForm form = new ModelForm("数据转存",3);
        form.addItem(
            FormInput.input("描述", "model.description").setEdit(edit).setSpan(3).setPlaceholder("请输入描述"),
            FormInput.selectItem("源数据表", "model.sourceTable",actionUrl("getTableOptions")+"?type=source").setEdit(edit).setPlaceholder("请选择源数据表"),
            FormInput.selectItem("保存表", "model.saveTable",actionUrl("getTableOptions")+"?type=save").setEdit(edit).setPlaceholder("请选择保存表"),
            FormInput.radio("触发条件", "model.triggerCondition", "api.model.ApiConvertData!triggerCondition").setEdit(edit).setPlaceholder("请选择触发条件"),
            FormTest.test("model.triggerCondition=='T'",
                FormInput.radio("定时时长", "model.timerLong", "api.model.ApiConvertData!timerLong").setEdit(edit).setSpan(2).setPlaceholder("请选择定时时长"),
                FormInput.dateTime("最后执行时间", "model.lastDate").setEdit(edit).setPlaceholder("请输入最后一次执行时间"),
                FormInput.radio("插入条件", "model.timerCondition", "api.model.ApiConvertData!timerCondition").setEdit(edit).setSpan(3).setPlaceholder("请选择插入条件")
            ),
            FormInput.selectItem("数据处理", "model.dataHandler","action/api/apiAuthInter/getDataHandlerOptions?tableOid=",true).setEdit(edit).setSpan(3).setPlaceholder("请选择数据处理")
        )
        .addData("model",model)
        .addButton(
            edit?FormButton.pri("保存","doSave"):null
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model,columnList:this.columnList}")
                    .success("backFlag")
        );

        TableForm table=new TableForm("列对应关系").setEdit(edit,edit,"{}");
        table.addColumn(
            TableColumn.INDEX_COLUMN,
            TableColumn.text("源数据表列","sourceColumn").setDict("'"+actionUrl("getSourceColumnOptions")+"?oid='+model.sourceTable").setAlign(Align.CENTER)
                .setEdit(TableEdit.selectTree("'"+actionUrl("getSourceColumnOptions")+"?oid='+model.sourceTable")),
            TableColumn.text("保存表列","saveColumn").setDict("'"+actionUrl("getSaveColumnOptions")+"?oid='+model.saveTable").setAlign(Align.CENTER)
                .setEdit(TableEdit.selectItem("'"+actionUrl("getSaveColumnOptions")+"?oid='+model.saveTable"))
        )
        .setData("columnList",columnList);
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(table)
        .addForm(
            new CustomForm("提示",false)
            .addElement(
                Element.tag("a-alert").A("message","提示").A("show-icon")
                .E(
                    Element.tag("template").A("#description")
                    .E(
                        Element.tag("div").E("自动触发：根据ModelUpdateUtil和TableUpdateUtil执行操作后触发。"),
                        Element.tag("div").E("定时触发：根据最后执行时间，按照定时时长持续触发。"),
                        Element.tag("div").E("保存表列必须有oid列。")
                    )
                )
            )
        );
    }
    /*
     * 数据转存列表
     */
    public VueResult allList() throws Exception {
        boolean power=hasAdminOperPower(getStatusPower());
        VueListResult result=getVueListResult("数据转存列表",ApiConvertData.class,actionUrl("allList"));
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.setLineClamp(2);
        result.addCol(toTextColumn("描述", "description", 100, true));
        result.addCol(toTextColumn("触发条件", "triggerCondition", 100, true).setDictType("api.model.ApiConvertData!triggerCondition"));
        result.addCol(toDateTimeColumn("最后执行时间", "lastDate", 120, true).setDateFormat(DateUtil.YYYY_MM_DD_HH_MM_SS));
        result.addCol(toTextColumn("原数据表", "sourceTable", 150, true).setDictType(actionUrl("getTableOptions")+"?type=source"));
        result.addCol(toTextColumn("保存表", "saveTable", 150, true).setDictType(actionUrl("getTableOptions")+"?type=save"));
        result.addCol(toTextColumn("数据处理", "dataHandler", 150, true).setDictType("action/api/apiAuthInter/getDataHandlerOptions?tableOid="));
        result.addCol(toStatusColumn(power, true).setDictType("api.model.ApiConvertData!status"));
        result.addCol(toSpaceColumn("操作", 100,
            ListButton.modal("{{record.status=='9'?'修改':'查看'}}", ButtonType.PRIMARY,actionUrl("toEdit"),1200, SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.modal("新增", ButtonType.PRIMARY,actionUrl("toEdit"),1200, SuccessMethod.REFRESH)
        );
        //排序 result.addOrder
        //查询条件 result.addCondition
        return result;
    }
    @Override
    public String[] getStatusPower() {
        return new String[]{"manage_api_power"};
    }

    public List<JSONObject> getColumnList() {
        return columnList;
    }

    public void setColumnList(List<JSONObject> columnList) {
        this.columnList = columnList;
    }

    @Override
    public ApiConvertData getModel() {
        return model;
    }
    public void setModel(ApiConvertData model) {
        this.model = model;
    };
}
